
package com.wjr.braveheart.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Build.VERSION;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewParent;
import android.widget.TextView;

import androidx.annotation.LayoutRes;


/**
 * Copyright upu173.com
 * Author 还如一梦中
 * Date 2016/6/14 17:54
 * Email 396196516@qq.com
 * Info View工具类
 */

public class ViewAdapterUtils {

    /**
     * UI设计的基准宽度.
     */
    public static int DESIGN_WIDTH = 360;

    /**
     * UI设计的基准高度.
     */
    public static int DESIGN_HEIGHT = 720;

    /**
     * 实际屏幕的宽度
     */
    public static int DISPLAY_WIDTH;

    /**
     * 实际屏幕的高度
     */
    public static int DISPLAY_HEIGHT;

    /**
     * 是否显示状态栏
     */
    public static boolean HAS_STATUS_BAR = false;

    /**
     * 无效值
     */
    public static final int INVALID = Integer.MIN_VALUE;

    /**
     * @param activity     要适配的界面Activity
     * @param layoutResID  Activity布局ID
     * @param hasStatusBar 是否显示标题栏
     */
    public static void setContentView(Activity activity, @LayoutRes int layoutResID, boolean hasStatusBar) {
        HAS_STATUS_BAR = hasStatusBar;
        getScreenInfo(activity);
        View contentView = View.inflate(activity, layoutResID, null);
        scaleContentView(contentView);
        activity.setContentView(contentView);
    }

    /**
     * 获取屏幕宽度和高度
     *
     * @param activity
     */
    private static void getScreenInfo(Activity activity) {
        if (DISPLAY_WIDTH != 0 && DISPLAY_HEIGHT != 0) {
            return;
        }

        DisplayMetrics displayMetrics = new DisplayMetrics();
        Display display = activity.getWindowManager().getDefaultDisplay();
        if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealMetrics(displayMetrics);
        } else {
            display.getMetrics(displayMetrics);
        }
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;

        if (HAS_STATUS_BAR) {
            height -= getStatusBarHeight(activity);
        }

        DISPLAY_WIDTH = width;
        DISPLAY_HEIGHT = height;
    }

    /**
     * View树递归调用做适配.
     * 要求布局中的单位都用px并且和美工的设计图尺寸一致，包括所有宽高，Padding,Margin,文字大小
     *
     * @param contentView
     */
    public static void scaleContentView(View contentView) {
        scaleView(contentView);
        if (contentView instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) contentView;
            if (viewGroup.getChildCount() > 0) {
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    View view = viewGroup.getChildAt(i);
                    scaleContentView(view);
                }
            }
        }
    }


    /**
     * 按比例缩放View，以布局中的尺寸为基准
     *
     * @param view
     */
    public static void scaleView(View view) {

        if (!isNeedScale(view)) {
            return;
        }

        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (null != params) {
            int width = INVALID;
            int height = INVALID;
            if (params.width != ViewGroup.LayoutParams.WRAP_CONTENT
                    && params.width != ViewGroup.LayoutParams.MATCH_PARENT) {
                width = params.width;
            }

            if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT
                    && params.height != ViewGroup.LayoutParams.MATCH_PARENT) {
                height = params.height;
            }

            //设置ViewSize
            setViewSize(view, width, height);

            // 设置ViewPadding
            setPadding(view, view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
        }

        // 设置ViewMargin
        if (view.getLayoutParams() instanceof MarginLayoutParams) {
            MarginLayoutParams mMarginLayoutParams = (MarginLayoutParams) view
                    .getLayoutParams();
            if (mMarginLayoutParams != null) {
                setMargin(view, mMarginLayoutParams.leftMargin, mMarginLayoutParams.topMargin, mMarginLayoutParams.rightMargin, mMarginLayoutParams.bottomMargin);
            }
        }

        if (VERSION.SDK_INT >= 16) {
            //最大最小宽高
            int minWidth = scaleValue(view.getMinimumWidth());
            int minHeight = scaleValue(view.getMinimumHeight());
            view.setMinimumWidth(minWidth);
            view.setMinimumHeight(minHeight);
        }

        //设置文字大小
        if (view instanceof TextView) {
            TextView textView = (TextView) view;
            setTextSize(textView, textView.getTextSize());
        }

    }

    /**
     * 根据屏幕款或高进行缩放.获取缩放后的值
     *
     * @param pxValue the px value
     * @return the int
     */
    public static int scaleValue(float pxValue) {

        if (pxValue == 0) {
            return 0;
        }
        float scale = 1;
        try {
            int width = DISPLAY_WIDTH;
            int height = DISPLAY_HEIGHT;
            //解决横屏比例问题
            if (width > height) {
                width = DISPLAY_HEIGHT;
                height = DISPLAY_WIDTH;
            }
            float scaleWidth = (float) width / DESIGN_WIDTH;
            float scaleHeight = (float) height / DESIGN_HEIGHT;
            scale = Math.min(scaleWidth, scaleHeight);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Math.round(pxValue * scale);
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {

        int result = 0;
        try {
            int resourceId = context.getResources().getIdentifier(
                    "status_bar_height", "dimen", "android");

            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }

        return result;

    }

    /**
     * 是否需要Scale.
     *
     * @param view
     * @return
     */
    public static boolean isNeedScale(View view) {
        return true;
    }


    /**
     * 缩放文字大小,这样设置的好处是文字的大小不和密度有关，
     * 能够使文字大小在不同的屏幕上显示比例正确
     *
     * @param textView   button
     * @param sizePixels px值
     * @return
     */
    public static void setTextSize(TextView textView, float sizePixels) {
        float scaledSize = scaleTextSizeValue(sizePixels);
        textView.setIncludeFontPadding(false);//清除TextView字体周边空白
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, scaledSize);
    }

    /**
     * 获取文字大小的缩放值
     *
     * @param sizePixels
     * @return
     */
    private static float scaleTextSizeValue(float sizePixels) {
        double designDiagonal = Math.sqrt(Math.pow(DESIGN_WIDTH, 2) + Math.pow(DESIGN_HEIGHT, 2));
        double displayDiagonal = Math.sqrt(Math.pow(DISPLAY_WIDTH, 2) + Math.pow(DISPLAY_HEIGHT, 2));
        double textPixelsRate = displayDiagonal / designDiagonal;
        Log.e("scaleTextSizeValue", "设置文字大小");
        return (float) (sizePixels * textPixelsRate);
    }


    /**
     * 设置View的PX尺寸
     *
     * @param view         如果是代码new出来的View，需要设置一个适合的LayoutParams
     * @param widthPixels
     * @param heightPixels
     */
    public static void setViewSize(View view, int widthPixels, int heightPixels) {
        int scaledWidth = scaleValue(widthPixels);
        int scaledHeight = scaleValue(heightPixels);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params == null) {
            Log.e("ViewAdapterUtils.class", "setViewSize出错,View.getLayoutParams==null，需要设置一个适合的LayoutParams");
            return;
        }
        if (widthPixels != INVALID) {
            params.width = scaledWidth;
        }
        if (heightPixels != INVALID && heightPixels != 1) {
            params.height = scaledHeight;
        }
        view.setLayoutParams(params);
    }

    /**
     * 设置PX padding.
     *
     * @param view   the view
     * @param left   the left padding in pixels
     * @param top    the top padding in pixels
     * @param right  the right padding in pixels
     * @param bottom the bottom padding in pixels
     */
    public static void setPadding(View view, int left,
                                  int top, int right, int bottom) {
        int scaledLeft = scaleValue(left);
        int scaledTop = scaleValue(top);
        int scaledRight = scaleValue(right);
        int scaledBottom = scaleValue(bottom);
        view.setPadding(scaledLeft, scaledTop, scaledRight, scaledBottom);
    }

    /**
     * 设置 PX margin.
     *
     * @param view   the view
     * @param left   the left margin in pixels
     * @param top    the top margin in pixels
     * @param right  the right margin in pixels
     * @param bottom the bottom margin in pixels
     */
    public static void setMargin(View view, int left, int top,
                                 int right, int bottom) {
        int scaledLeft = scaleValue(left);
        int scaledTop = scaleValue(top);
        int scaledRight = scaleValue(right);
        int scaledBottom = scaleValue(bottom);

        if (view.getLayoutParams() instanceof MarginLayoutParams) {
            MarginLayoutParams mMarginLayoutParams = (MarginLayoutParams) view
                    .getLayoutParams();
            if (mMarginLayoutParams != null) {
                if (left != INVALID) {
                    mMarginLayoutParams.leftMargin = scaledLeft;
                }
                if (right != INVALID) {
                    mMarginLayoutParams.rightMargin = scaledRight;
                }
                if (top != INVALID) {
                    mMarginLayoutParams.topMargin = scaledTop;
                }
                if (bottom != INVALID) {
                    mMarginLayoutParams.bottomMargin = scaledBottom;
                }
                view.setLayoutParams(mMarginLayoutParams);
            }
        }

    }

    /**
     * 获得这个View的宽度
     * 测量这个view，最后通过getMeasuredWidth()获取宽度.
     *
     * @param view 要测量的view
     * @return 测量过的view的宽度
     */
    public static int getViewWidth(View view) {
        measureView(view);
        return view.getMeasuredWidth();
    }

    /**
     * 获得这个View的高度
     * 测量这个view，最后通过getMeasuredHeight()获取高度.
     *
     * @param view 要测量的view
     * @return 测量过的view的高度
     */
    public static int getViewHeight(View view) {
        measureView(view);
        return view.getMeasuredHeight();
    }

    /**
     * 从父亲布局中移除自己
     *
     * @param v
     */
    public static void removeSelfFromParent(View v) {
        ViewParent parent = v.getParent();
        if (parent != null) {
            if (parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(v);
            }
        }
    }

    /**
     * 测量这个view
     * 最后通过getMeasuredWidth()获取宽度和高度.
     *
     * @param view 要测量的view
     * @return 测量过的view
     */
    public static void measureView(View view) {
        ViewGroup.LayoutParams p = view.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
        }
        view.measure(childWidthSpec, childHeightSpec);
    }


}
